package com.fwtai.tool;

import java.security.SecureRandom;

/**
 * 生成分布式的id或code
 * @作者 田应平
 * @版本 v1.0
 * @创建时间 2019年11月4日 21:28:01
 * @QQ号码 444141300
 * @Email service@dwlai.com
 * @官网 http://www.fwtai.com
*/
public final class ToolCode{

  public static String[] generator(){
    final String[] resUrl = new String[4];
    for (int i = 0; i < 4; i++) {
      resUrl[i] = invitationCode();
    }
    return resUrl;
  }

  //邀请码
  public static String invitationCode(){
    return createKey(6);
  }

  //商品防伪码
  public static String securityCode(){
    return createKey(6);
  }

  //生成替换之前的手机号
  public static String displacePhone(){
    return createKey(11);
  }

  //申请接入时的标识
  public static String getKey(){
    return createKey(32);
  }

  private static String createKey(final int size){
    final char[] alphabet = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
    final int mask = (2 << (int)Math.floor(Math.log((alphabet.length - 1)) / Math.log(2.0D))) - 1;
    final int step = (int)Math.ceil(1.6D * (double)mask * (double)size / (double)alphabet.length);
    final StringBuilder idBuilder = new StringBuilder();
    while(true) {
      final byte[] bytes = new byte[step];
      new SecureRandom().nextBytes(bytes);
      for(int i = 0; i < step; ++i) {
        final int alphabetIndex = bytes[i] & mask;
        if (alphabetIndex < alphabet.length) {
          idBuilder.append(alphabet[alphabetIndex]);
          if (idBuilder.length() == size) {
            return idBuilder.toString();
          }
        }
      }
    }
  }
}